package com.woniu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.exception.LXLGException;
import com.woniu.product.common.CouponResultCode;
import com.woniu.product.infra.model.Coupon;
import com.woniu.product.infra.mapper.CouponMapper;
import com.woniu.product.infra.model.Sku;
import com.woniu.product.service.CouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.product.service.SkuService;
import com.woniu.product.service.dto.SkuCanUseCouponDto;
import com.woniu.product.service.form.ProvideCouponServiceParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 优惠劵表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2022-11-26
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    @Resource
    private SkuService skuService;

    /**
     * 查询skuId可使用的券
     *
     * @param skuId
     * @return
     */
    @Override
    public List<SkuCanUseCouponDto> searchCouponBySkuId(Integer skuId) {
        Sku sku = skuService.getById(skuId);
        List<SkuCanUseCouponDto> SkuCanUseCouponDtos = new ArrayList<>();
        QueryWrapper<Coupon> qw = new QueryWrapper<>();
        qw.eq("spu_id", sku.getSpuId());
        List<Coupon> coupons = list(qw);
        log.info("可使用的优惠券：{}", coupons);
        if (coupons.isEmpty()) {
            throw new LXLGException(CouponResultCode.COUPON_NOT_FOUND);
        }
        for (Coupon coupon : coupons) {
            if (DateUtil.isIn(new Date(), coupon.getValidStartTime(), coupon.getValidEndTime())) {
                System.out.println(1);
                log.info("new Date：{}", new Date());
                log.info("coupon.getValidStartTime：{}", coupon.getValidStartTime());
                log.info("coupon.getValidEndTime：{}", coupon.getValidEndTime());
                log.info("可使用的优惠券：{}", coupon);
                SkuCanUseCouponDtos.add(BeanUtil.copyProperties(coupon, SkuCanUseCouponDto.class));
            }
        }
        return SkuCanUseCouponDtos;
    }

    /**
     * 发放优惠券
     *
     * @param provideCouponServiceParam
     */
    @Override
    public void provideCoupon(ProvideCouponServiceParam provideCouponServiceParam) {
        Coupon coupon = BeanUtil.copyProperties(provideCouponServiceParam, Coupon.class);
        coupon.setUsedCount(0);
        coupon.setStatus(1);
        coupon.setCreateTime(new Date());
        save(coupon);
    }
}
